<!--
 * @Description: 渠道活码和群活码
 * @Author: lixianggang
 * @Date: 2022-10-17 14:25:24
 * @LastEditors: xuqinyang
 * @LastEditTime: 2022-12-15 16:17:19
-->
<template>
  <div class="verbal-wrap">
    <div class="page-content">
      <div v-loading="pageLoading" class="content-group">
        <div class="group-title">
          <div class="title-name" @click="handleClickAll">
            <i :class="['el-icon-caret-bottom', iconRotate ? 'icon-rotate-90' : 'icon-rotate-0']"
              style="color:#ccc"></i>全部
          </div>
          <div class="title-btn" @click="addOrUpdateGroup('add')">
            <i class="el-icon-circle-plus-outline"></i>添加
          </div>
        </div>
        <div :class="iconRotate ? 'group-name' : 'group-name-unfold'">
          <div v-for="item in groupList" :key="item.id"
            :class="['group-title', 'group-item', { 'group-item-active': currentGroupIndex === item.id }]"
            @click="switchGroup(item.id, item)">
            <div class="item-name">{{ item.name }}</div>
            <div>
              <el-dropdown>
                <i class="el-icon-more"></i>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item>
                    <el-button type="text" @click="addOrUpdateGroup('update', item)">编辑
                    </el-button>
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <el-button type="text" @click="deleteGroup(item)">删除</el-button>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </div>
          </div>
        </div>
      </div>
      <div class="content-table">
        <div style="border-bottom: 1px solid #eee;">
          <NormalForm :pageTitle="pageTitle" :isShowCard="false" :operateForm="queryForm" :formList="formList"
            @handleQuery="handleQuery" @handleReset="handleReset"></NormalForm>
        </div>
        <div style="text-align: right; margin: 20px 0;">
          <el-button v-hasPermi="['admin:code:add']" icon="el-icon-plus" type="primary" @click="createCode(tabsType)">创建活码
          </el-button>
        </div>
        <div>
          <el-table v-loading="tableLoading" :data="tableData" :row-style="{ height: '40px' }" height="442px">
            <el-table-column align="center" label="序号" type="index" width="50"></el-table-column>
            <el-table-column key="activityName" align="center" label="名称" prop="activityName" show-overflow-tooltip
              :width="180"></el-table-column>
            <template v-if="tabsType === '0'">
              <el-table-column key="scanNum" align="center" label="添加好友次数" prop="scanNum" width="110"></el-table-column>
              <el-table-column key="creatTime" :width="160" align="center" label="创建时间"
                prop="creatTime"></el-table-column>
              <el-table-column key="userNames" :width="160" align="center" label="使用员工" prop="userNames"
                show-overflow-tooltip>
                <template slot-scope="scope">
                  <div class="text-color">{{ scope.row.userNames }}</div>
                </template>
              </el-table-column>
              <el-table-column key="guaranteeUserNames" :width="140" align="center" label="兜底员工" prop="guaranteeUserNames"
                show-overflow-tooltip></el-table-column>
              <el-table-column key="options" :min-width="260" align="center" label="标签">
                <template slot-scope="scope">
                  <tagGroupShowTable :tagGroup="scope.row.tagVOS" />
                </template>
              </el-table-column>
              <el-table-column align="center" fixed="right" label="操作" width="160">
                <template slot-scope="scope">
                  <el-button v-hasPermi="['admin:code:query']" type="text"
                    @click="checkVerbal('detail', scope.row.qrId)">详情
                  </el-button>
                  <el-button v-hasPermi="['admin:code:export']" type="text" @click="downQrCode(scope.row.qrCode)">下载
                  </el-button>
                  <el-button v-hasPermi="['admin:code:edit']" type="text" @click="checkVerbal('edit', scope.row.qrId)">编辑
                  </el-button>
                  <el-button v-hasPermi="['admin:code:remove']" type="text" @click="deleteItem(scope.row.qrId, 1)">删除
                  </el-button>
                </template>
              </el-table-column>
            </template>
            <template v-if="tabsType === '1'">
              <el-table-column :min-width="150" align="center" label="创建时间" prop="createTime"></el-table-column>
              <el-table-column :width="160" align="center" label="使用员工" prop="userName">
                <template slot-scope="scope">
                  <div class="text-color">{{ scope.row.userName }}</div>
                </template>
              </el-table-column>
              <el-table-column align="center" label="添加好友数" prop="totalScanTimes" width="140"></el-table-column>
              <el-table-column :width="260" align="center" label="标签" prop="materialTag">
                <template slot-scope="scope">
                  <tagGroupShowTable :tagGroup="scope.row.tagVOS" />
                </template>
              </el-table-column>
              <el-table-column align="center" prop="groupWays" label="拉群方式" width="120"></el-table-column>
              <el-table-column align="center" label="群聊" prop="groupName" width="180">
                <template slot-scope="{ row }">
                  <div v-if="row.groupName">
                    {{ row.groupName[0] }} ({{ row.groupName.length }})
                    <el-tag v-if="row.groupWays === 0 && row.flag === true">
                      已完成
                    </el-tag>
                    <el-tag v-else-if="row.groupWays === 0 && row.flag === false">
                      拉人中
                    </el-tag>
                  </div>
                  <div v-else>
                    <el-tag>拉人中</el-tag>
                  </div>
                </template>
              </el-table-column>
              <el-table-column :width="160" align="center" label="创建员工" prop="createBy">
                <template slot-scope="scope">
                  <div class="text-color">{{ scope.row.createBy }}</div>
                </template>
              </el-table-column>
              <el-table-column align="center" fixed="right" label="操作" width="180">
                <template slot-scope="scope">
                  <el-button v-hasPermi="['we:groupCode:query']" type="text" @click="detailpage(scope)">详情</el-button>
                  <el-button v-hasPermi="['we:groupCode:download']" type="text"
                    @click="downQrCode(scope.row.codeUrl)">下载</el-button>
                  <el-button type="text" @click="updateTrick(scope)">编辑</el-button>
                  <el-button v-hasPermi="['we:groupCode:delete']" type="text"
                    @click="deleteItem(scope.row.id, 2)">删除</el-button>
                </template>
              </el-table-column>
            </template>
          </el-table>
          <NormalPagination :currentPage="queryForm.pageNum" :pageSize="queryForm.pageSize" :total="total"
            @handleSizeChange="handleSizeChange" @handleCurrentChange="handleCurrentChange"></NormalPagination>
        </div>
      </div>
    </div>
    <!-- 新建或修改分组 -->
    <el-dialog :show-close="false" :close-on-click-modal="false" :close-on-press-escape="false"
      :title="`${addOrUpdate === 'add' ? '新建' : '编辑'}分组`" :visible.sync="groupVisible" width="520px">
      <el-form ref="groupForm" :model="groupForm" :rules="rules">
        <el-form-item label="请输入分组名称" label-width="130px" prop="name">
          <el-input v-model="groupForm.name" clearable maxlength="32"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="handleGroupDialogClose">取 消</el-button>
        <el-button type="primary" @click="onAddOrUpdateGroup">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 删除分组 -->
    <el-dialog :show-close="false" :close-on-click-modal="false" :close-on-press-escape="false"
      :visible.sync="deleteFailureVisible" title="删除失败" width="460px">
      分组下存在活码，无法删除！
      <div slot="footer">
        <el-button type="primary" @click="deleteFailureVisible = false">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog :show-close="false" :close-on-click-modal="false" :close-on-press-escape="false"
      :visible.sync="deleteVisible" title="删除确认" width="460px">
      <div>确认删除该条数据？</div>
      <div slot="footer">
        <el-button @click="deleteCancel">取 消</el-button>
        <el-button type="primary" @click="deleteConfirm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  deleteGroupTool,
  getGroupList,
  groupCode,
  removInginterface,
  verbalDelete,
  verbalList,
} from '@/api/operate/verbalTrick'
import {
  categoryAddPersonal,
  categoryDelPersonal,
  categoryEditPer,
} from '@/api/article/group'

export default {
  data() {
    return {
      tabsType: '0',
      groupList: [],
      pageTitle: '',
      queryForm: {
        activityName: '',
        deptId: null,
        createCodeList: '',
        pageNum: 1,
        pageSize: 20,
      },
      formList: [
        {
          label: '活码名称',
          value: '',
          prop: 'activityName',
          type: 'INPUT',
          emunName: ''
        },
        {
          label: '管理机构',
          value: null,
          prop: 'deptId',
          type: 'MANAGE_COM',
          emunName: ''
        },
        {
          label: '创建人',
          value: '',
          prop: 'createCodeList',
          type: 'STAFF',
          emunName: ''
        },
      ],
      tableLoading: false,
      total: 0,
      tableData: [],
      iconRotate: false,
      currentGroupIndex: '',
      currentGroup: '',
      groupForm: {
        name: '',
      },
      rules: {
        name: [{ required: true, message: '请输入分组名称', trigger: 'blur' }],
      },
      pageLoading: false,
      groupVisible: false,
      deleteFailureVisible: false,
      addOrUpdate: '',
      deleteVisible: false,
      delQrId: '',
      delMsg: null, // 1: 渠道活码 2：群活码
      particulars: 1,
    }
  },
  mounted() {
    if (this.$route.query.is_person === '2') {
      this.tabsType = '1'
    }
    this.tabsType = this.$route.name === 'ChannelLiveCode' ? '0' : '1'
    this.pageTitle = this.$route.name === 'ChannelLiveCode' ? '渠道活码' : '群活码'
    this.handleGetGroupList()
    this.handleQuery()
  },
  methods: {
    handleGetGroupList() {
      const params = {
        levelType: 3,
        tabsType: this.tabsType,
        mediaType: +this.tabsType + 1,
      }
      this.pageLoading = true
      getGroupList(params).then((res) => {
        this.pageLoading = false
        if (res.code === 200) {
          this.groupList = res.data || []
        }
      }).catch(() => {
        this.pageLoading = false
      })
    },
    // 全部
    handleClickAll() {
      this.iconRotate = !this.iconRotate
      if (this.iconRotate) {
        this.currentGroup = ''
        this.currentGroupIndex = ''
        this.handleReset();
      }
    },
    switchGroup(key, item) {
      if (this.currentGroupIndex === key) return
      this.currentGroupIndex = key
      this.currentGroup = item
      this.handleReset()
    },
    // 删除分组
    deleteGroup(item) {
      this.$confirm('此操作将永久删除分组, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        if (this.tabsType === '0') {
          deleteGroupTool(item.id).then((res) => {
            this.handleGetGroupList()
            this.handleReset()
            this.$message.success('删除成功!')
          }).catch(() => { })
        } else {
          categoryDelPersonal(item.id).then((res) => {
            this.handleGetGroupList()
            this.handleReset()
            this.$message.success('删除成功!')
          }).catch(() => { })
        }
      })
    },
    // 查询
    handleQuery() {
      this.queryForm.pageNum = 1;
      this.getListFn()
    },
    getListFn() {
      this.tableLoading = true
      const params = {
        activityName: this.queryForm.activityName,
        deptId: this.queryForm.deptId,
        createCodeList: this.queryForm.createCodeList + '',
        levelType: 3,
        mediaType: +this.tabsType + 1,
        categoryId: this.currentGroup?.id,
        tabsType: this.tabsType,
        pageNum: this.queryForm.pageNum,
        pageSize: this.queryForm.pageSize,
      }
      if (+this.tabsType === 0) {
        params.groupId = this.currentGroup?.id
        verbalList(params).then((res) => {
          if (res.code === 200) {
            this.tableData = res.rows || []
            this.total = res.total || 0
          }
          this.tableLoading = false
        })
      } else {
        groupCode(params).then((res) => {
          if (res.code === 200) {
            this.tableData = res.rows || []
            this.tableData.forEach((item) => {
              if (item.groupWays == '0') {
                item.groupWays = '群二维码拉群'
              } else if (item.groupWays == '1') {
                item.groupWays = '企微活码拉群'
              } else if (item.groupWays == 2) item.groupWays = '个人群活码拉群'
              else if (item.groupWays == 3) item.groupWays = '标签拉群'
            })
            this.total = res.total || 0
          }
          this.tableLoading = false
        })
      }
    },
    //重置
    handleReset() {
      this.queryForm = {
        activityName: '',
        createBy: '',
        deptId: null,
        createCodeList: '',
        pageNum: 1,
        pageSize: 20,
      };
      this.getListFn()
    },
    handleSizeChange(val) {
      this.queryForm.pageNum = 1
      this.queryForm.pageSize = val
      this.getListFn()
    },
    handleCurrentChange(val) {
      this.queryForm.pageNum = val
      this.getListFn()
    },
    // 创建活码
    createCode(tabsType) {
      if (tabsType === '0') {
        this.$router.push({ path: 'channelCode' })
      } else {
        this.$router.push({ path: 'addCode' })
      }
    },
    // 下载
    downQrCode(img) {
      if (img) {
        const imgUrl = img.materialUrl
        const a = document.createElement('a')
        fetch(imgUrl)
        fetch(img).then((res) => res.blob()).then((blob) => {
          a.href = URL.createObjectURL(blob)
          a.download = img.materialName
          a.download = img + '.png'
          document.body.appendChild(a)
          a.click()
          window.URL.revokeObjectURL(a.href)
          document.body.removeChild(a)
        })
      } else {
        this.$message({ message: '暂无二维码!' })
      }
    },
    // 群活码编辑
    updateTrick(scope) {
      this.particulars = 2
      this.$router.push({
        path: 'editCode',
        query: {
          id: scope.row.id,
          groupWays: scope.row.groupWays,
          particulars: this.particulars,
        },
      })
    },
    // 群活码详情
    detailpage(scope) {
      this.particulars = 3
      this.$router.push({
        path: 'codeDetail',
        query: {
          id: scope.row.id,
          groupWays: scope.row.groupWays,
          particulars: this.particulars,
        },
      })
    },
    // 渠道活码详情、编辑
    checkVerbal(type, id) {
      let path = type === 'edit' ? 'channelCodeEdit' : 'channelCodeDetail'
      let fromDetail = type === 'detail'
      this.$router.push({
        path,
        query: { fromDetail, id },
      })
    },
    // 删除活码
    deleteItem(id, msg) {
      this.delQrId = id
      this.delMsg = msg
      this.deleteVisible = true
    },
    // 删除分组
    deleteConfirm() {
      if (this.delMsg === 1) {
        verbalDelete({ id: this.delQrId }).then((res) => {
          this.deleteVisible = false
          if (res.code === 200) {
            this.$message.success(res.msg || '操作成功')
            this.handleReset()
          }
        })
      } else if (this.delMsg === 2) {
        removInginterface({ id: this.delQrId })
          .then((res) => {
            this.deleteVisible = false
            if (res.code === 200) {
              this.$message.success(res.msg || '操作成功')
              this.handleReset()
            }
          })
          .catch(() => {
            this.tableLoading = false
          })
      }
    },
    deleteCancel() {
      this.deleteVisible = false
      this.delQrId = ''
      this.delMsg = 1
    },
    // 编辑分组
    addOrUpdateGroup(flag, item) {
      this.groupVisible = true
      this.addOrUpdate = flag
      flag === 'update' && (this.groupForm.name = item?.name)
    },
    handleGroupDialogClose() {
      this.groupVisible = false
      this.$refs.groupForm.resetFields()
    },
    // 保存分组
    onAddOrUpdateGroup() {
      this.$refs.groupForm.validate(async (valid) => {
        if (valid) {
          const params = {
            levelType: 3, // 活码都是3
            tabsType: this.tabsType,
            mediaType: +this.tabsType + 1,
            ...this.groupForm,
          }
          let res = ''
          if (this.addOrUpdate === 'add') {
            res = await categoryAddPersonal(params)
          } else if (this.addOrUpdate === 'update') {
            params.id = this.currentGroup.id
            res = await categoryEditPer(params)
          }
          if (res.code === 200) {
            this.handleGroupDialogClose()
            this.handleGetGroupList()
            this.$message.success(res.msg || '操作成功')
          } else {
            this.$message.error(res.msg || '操作失败')
          }
        } else {
          return false
        }
      })
    },
  },
}
</script>

<style lang="scss" scoped>
@import '@/styles/base.scss';

.verbal-wrap {
  background: #fff;
  padding: 0;
  height: 100%;

  .page-content {
    display: flex;
    margin-left: 24px;

    .content-group {
      width: 200px;
      border-right: 1px solid #f1f1f1;
      padding: 12px 15px 0 0;
      font-size: 12px;

      .group-title {
        height: 37px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        cursor: pointer;

        i {
          margin-right: 5px;
        }

        .title-name {
          flex: 1;
          .icon-rotate-90 {
            transition: transform 0.2s, -webkit-transform 0.2s;
            transform: rotateZ(-90deg);
            color: #C0C4CC;
          }
          .icon-rotate-0 {
            transition: transform 0.2s, -webkit-transform 0.2s;
            transform: rotate(0deg);
            color: #C0C4CC;
          }
        }
        .title-btn {
          color: #082aff;

          &:hover {
            opacity: 0.7;
          }
        }
      }
      .group-name {
        max-height: 0;
        overflow: hidden;
      }
      .group-name-unfold {
        max-height: calc(100% - 30px);
        transition: max-height 0.3s;
        padding: 0 10px 0 20px;
        overflow: scroll;
        &::-webkit-scrollbar {
          width: 0;
        }
        -ms-overflow-style: none;
        overflow: -moz-scrollbars-none;
      }
      .group-item-active {
        background-color: #fff2ee;
      }
    }

    .content-table {
      width: calc(100% - 200px);
      padding: 16px 15px 0 15px;
    }
  }
}

.text-color {
  color: #082aff;
}
</style>
